<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" placeholder="请选择部门负责人">
          <el-option
            v-for="item in employees"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="form.introduce"
          placeholder="1-300个字符"
          type="textarea"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="small"
          @click="deptSubmit"
        >确定</el-button>
        <el-button size="small" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple, addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
export default {
  name: 'DeptDialog',
  props: {
    parentId: {
      type: [Number, String],
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 定义一个验证code是否存在的自定义函数
    const validCode = (rule, value, callback) => {
      // 将每一项的code提出来组成一个新数组
      let existCodeList = this.originList.map(item => item.code)
      // 判断是否为编辑状态
      if (this.isEdit) {
        // 编辑状态下将本身所对应的code从数组中删除
        // 具体先用当前编辑的parentId来筛选掉当前项，然后提取code生成新数组
        existCodeList = this.originList.filter(item => item.id !== this.parentId).map(item => item.code)
      }
      // 判断值是否在code数组中存在，存在抛出错误，不存在通过验证
      existCodeList.includes(value) ? callback(new Error(`部门编码${value}已存在`)) : callback()
    }

    // 定义验证部门名称在同级是否存在的自定义函数
    // 新增的公式：通过父级的id等于子集的pid 来获取要新增的同级部门
    // 编辑的公式：点击获取要编辑项的id，通过id获取pid来查询同级部门
    const validName = (rule, value, callback) => {
      // 通过pid等于上级的id来筛选出同级的部门，通过map将部门名称提取出来为一个新数组
      let existNameList = this.originList.filter(item => item.pid === this.parentId).map(item => item.name)
      // 判断是否为编辑状态
      if (this.isEdit) {
        // 获取当前编辑项的pid
        const pid = this.originList.find(item => item.id === this.parentId).pid
        // 通过pid获取同级部门名称，排除自身后通过map生成name新数组
        existNameList = this.originList.filter(item => item.pid === pid && item.id !== this.parentId).map(item => item.name)
      }
      // 判断新增的部门名称是否在数组中存在
      existNameList.includes(value) ? callback(new Error(`部门名称 ${value} 已存在`)) : callback()
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      employees: [], // 负责人列表

      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getEmployeeSimple()
    this.getDepartDetail()
  },
  methods: {
    // 新增部门
    async addDepartments() {
      const res = await addDepartments({ ...this.form, pid: this.parentId })
      //   console.log(res)
      this.$message.success(res.message)
      this.$emit('update-list')
    },
    // 编辑部门
    async updateDepartments() {
      const res = await updateDepartments(this.form)
      console.log(res)
      this.$message.success(res.message)
      this.$emit('update-list')
    },
    // 点击确认
    deptSubmit() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        this.isEdit ? this.updateDepartments() : this.addDepartments()
      })
    },
    // 取消
    cancel() {
      this.$emit('close')
    },
    // 获取负责人列表
    async getEmployeeSimple() {
      const res = await getEmployeeSimple()
      //   console.log(res)
      this.employees = res.data
    },
    // 获取部门详情
    async getDepartDetail() {
      if (this.isEdit) {
        const res = await getDepartDetail(this.parentId)
        // console.log(res)
        this.form = res.data
      }
    }

  }
}
</script>

<style lang="scss" scoped>
form.el-form {
  padding: 15px 60px 0 20px;
}
.el-select {
  width: 100%;
}
</style>
